<template>
  <div class="retro-container">
    <header class="retro-header">
      <h1 class="retro-title">GitHub STAR 时光机</h1>
      <p class="retro-subtitle">收藏仓库的时光机</p>
    </header>

    <div class="retro-controls">
      <a-row :gutter="[16, 16]" align="middle">
        <a-col :xs="24" :sm="12" :md="8">
          <a-select
            v-model:value="selectedCategory"
            placeholder="选择分类"
            class="retro-select"
            style="width: 100%"
            @change="handleFilterChange"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="category in categories" :key="category" :value="category">
              {{ category }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="12" :md="8">
          <a-input
            v-model:value="searchQuery"
            placeholder="搜索仓库..."
            class="retro-input"
            @input="handleFilterChange"
            allow-clear
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </a-col>
        <a-col :xs="24" :sm="12" :md="8">
          <a-select
            v-model:value="sortBy"
            placeholder="排序方式"
            class="retro-select"
            style="width: 100%"
            @change="handleFilterChange"
          >
            <a-select-option value="starred_at_desc">点赞时间 ↓</a-select-option>
            <a-select-option value="starred_at_asc">点赞时间 ↑</a-select-option>
            <a-select-option value="updated_desc">更新时间 ↓</a-select-option>
            <a-select-option value="updated_asc">更新时间 ↑</a-select-option>
            <a-select-option value="name_asc">名称 A-Z</a-select-option>
            <a-select-option value="name_desc">名称 Z-A</a-select-option>
          </a-select>
        </a-col>
      </a-row>
    </div>

    <div v-if="loading" class="retro-loading">
      加载中...
    </div>

    <div v-else>
      <div class="retro-stats">
        共找到 {{ filteredRepos.length }} 个仓库
      </div>

      <a-list
        :data-source="paginatedRepos"
        :pagination="paginationConfig"
        class="retro-list"
      >
        <template #renderItem="{ item }">
          <a-list-item class="retro-card">
            <div class="retro-card-header">
              <h3 class="retro-card-title">
                <a 
                  :href="item.url" 
                  target="_blank" 
                  rel="noopener noreferrer"
                  class="retro-link"
                >
                  {{ item.name }}
                </a>
              </h3>
              <span class="retro-card-category">{{ item.category }}</span>
            </div>
            
            <div class="retro-card-content">
              {{ item.summary }}
            </div>
            
            <div class="retro-card-footer">
              <span>
                <CalendarOutlined /> 
                点赞: {{ formatDate(item.starred_at) }}
              </span>
              <span>
                <ClockCircleOutlined />
                更新: {{ formatDate(item.last_updated) }}
              </span>
            </div>
          </a-list-item>
        </template>
      </a-list>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { SearchOutlined, CalendarOutlined, ClockCircleOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'

const loading = ref(true)
const repos = ref([])
const selectedCategory = ref('')
const searchQuery = ref('')
const sortBy = ref('starred_at_desc')
const currentPage = ref(1)
const pageSize = ref(10)

const categories = [
  'Web开发', '移动端开发', '嵌入式系统', '操作系统', '网络技术',
  '网络安全', '数据库', '人工智能（AI）', '大数据', '云计算',
  'DevOps', '游戏开发', '区块链', '编程语言', '工具与实用程序',
  '开源书籍/教程', '桌面应用', '音视频处理', '自动化脚本', '开源硬件', '其他'
]

const loadData = async () => {
  try {
    const response = await fetch('/result.json')
    repos.value = await response.json()
  } catch (error) {
    console.error('加载数据失败:', error)
    // 使用模拟数据作为后备
    repos.value = []
  } finally {
    loading.value = false
  }
}

const filteredRepos = computed(() => {
  let filtered = repos.value

  // 分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(repo => repo.category === selectedCategory.value)
  }

  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(repo => 
      repo.name.toLowerCase().includes(query) ||
      repo.url.toLowerCase().includes(query) ||
      repo.summary.toLowerCase().includes(query)
    )
  }

  return filtered
})

const sortedRepos = computed(() => {
  const sorted = [...filteredRepos.value]
  
  switch (sortBy.value) {
    case 'starred_at_asc':
      return sorted.sort((a, b) => new Date(a.starred_at) - new Date(b.starred_at))
    case 'starred_at_desc':
      return sorted.sort((a, b) => new Date(b.starred_at) - new Date(a.starred_at))
    case 'updated_asc':
      return sorted.sort((a, b) => new Date(a.last_updated) - new Date(b.last_updated))
    case 'updated_desc':
      return sorted.sort((a, b) => new Date(b.last_updated) - new Date(a.last_updated))
    case 'name_asc':
      return sorted.sort((a, b) => a.name.localeCompare(b.name))
    case 'name_desc':
      return sorted.sort((a, b) => b.name.localeCompare(a.name))
    default:
      return sorted
  }
})

const paginatedRepos = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return sortedRepos.value.slice(start, end)
})

const paginationConfig = computed(() => ({
  total: filteredRepos.value.length,
  pageSize: pageSize.value,
  current: currentPage.value,
  onChange: (page) => {
    currentPage.value = page
  },
  showSizeChanger: false,
  showQuickJumper: false,
  class: 'retro-pagination'
}))

const handleFilterChange = () => {
  currentPage.value = 1
}

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.retro-stats {
  text-align: center;
  font-size: 12px;
  color: #00ff00;
  margin-bottom: 20px;
  padding: 10px;
  background: rgba(0, 255, 0, 0.1);
  border: 1px solid #00ff00;
  border-radius: 4px;
}

.retro-list {
  background: transparent;
}

.retro-list .ant-list-item {
  border: none;
  padding: 0;
  margin-bottom: 16px;
}
</style>